package com.hzvdvmc.autosale.socket.manager;

import android.os.CountDownTimer;

import com.hzvdvmc.autosale.constant.CmdEnum;
import com.hzvdvmc.autosale.constant.GlobleCache;
import com.hzvdvmc.autosale.constant.TimeConstant;
import com.hzvdvmc.autosale.socket.SocketClientManager;
import com.hzvdvmc.autosale.socket.event.CommonEvent;
import com.hzvdvmc.autosale.util.EncodeUtil;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.NetworkUtils;
import com.hzvdvmc.autosale.util.StringUtil;
import com.hzvdvmc.autosale.util.ToastUtils;
import com.vilyever.socketclient.SocketClient;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.hzvdvmc.autosale.socket.manager.CheckNumUtil.getCheckNum;

/**
 * Created by william on 2018/4/21.
 */

public class SocketRequest {
    private CmdEnum cmdEnum;
    private SocketLisenter mLisenter;
    private CountDownTimer timer;
    private String tuneNO;
    private String orderNO;

    public void setTuneNO(String tuneNO) {
        this.tuneNO = tuneNO;
    }

    public void setOrderNO(String orderNO) {
        this.orderNO = orderNO;
    }

    public SocketRequest(CmdEnum cmdEnum) {
        this.cmdEnum = cmdEnum;
    }

    public void equence(final String data, final SocketLisenter lisenter) {

        this.mLisenter = lisenter;
        sendData(data);
        timer = new CountDownTimer(20 * TimeConstant.second, 5 * TimeConstant.second) {
            @Override
            public void onTick(long millisUntilFinished) {
                sendData(data);
            }

            @Override
            public void onFinish() {
                if (mLisenter == null) {
                    return;
                }
                mLisenter.onError("请求超时");
                mLisenter = null;
            }
        };
        timer.start();
        SocketRequestQuence.addQuence(this);
    }


    private void sendData(String data) {
//        CmdRequestManager.getInstance().sendComand(cmdEnum, data);
        String fullCommand = getFullCommand(cmdEnum, data);
        SocketClientManager.getInstance()
                .getSocketClient()
                .sendData(StringUtil.hexStringToBytes(fullCommand));
    }


    public void callBack(String cmdValue, String data) {
        if (mLisenter == null) {
            return;
        }

        if (cmdEnum.getValue().equals(cmdValue)) {
            timer.cancel();
            LogUtil.i("callback data :" + cmdEnum.getDesc() + "," + data);
            mLisenter.onResponse(data, tuneNO, orderNO);
            mLisenter = null;
        }
    }

    /**
     * 完整上传数据
     *
     * @param command 指令
     * @param data    中间的有效数据，需要转化成16进制
     * @return
     */
    private String getFullCommand(CmdEnum command, String data) {
//        LogUtil.p("socket 请求指令：" + command.getDesc());
        StringBuilder sb = new StringBuilder();
        sb.append(getHeader(command, data));
        //消息体command+data
        String bodyMsg = EncodeUtil.encoded(command.getValue() + StringUtil.convertStringToHex(data));
        sb.append(bodyMsg);
        sb.append(CmdEnum.END.getValue());
        String fullComand = sb.toString();
        LogUtil.i("[socket reqeust] " + command.getDesc() + ":" + fullComand + ",data:" + data);
        return fullComand;
    }


    /**
     * 获取包头
     *
     * @param command
     * @param data
     * @return
     */
    private String getHeader(CmdEnum command, String data) {
        String start = CmdEnum.START.getValue();
        String size = Integer.toHexString(data.length() + 1);
        //size是2个字节，也就是4位16进制
        //比如10进制16 那就是 000F,10进制4096 那就是0FFF
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4 - size.length(); i++) {
            sb.append("0");
        }
        size = sb.toString() + size;
        String checkNum = getCheckNum(command.getValue(), data);
        return start + size + checkNum;
    }
}
